package com.jblog.core.service.mail.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.jblog.core.exception.MailException;
import com.jblog.core.model.account.Account;
import com.jblog.core.model.mail.MailInfo;
import com.jblog.core.service.mail.MailService;

import freemarker.template.Template;
import freemarker.template.TemplateException;

public class MailServiceImpl implements MailService {
   
    private String from;
    private @Autowired JavaMailSender sender;  
    private @Autowired FreeMarkerConfigurer freemarkerConfigurer;  

    @Override
    public void sendMail(MailInfo mail) {
        try {
            sender.send(toMsg(mail));
        } catch (MessagingException e) {
            throw new MailException(e);
        }
    }
    
    private MimeMessage toMsg(MailInfo mail) throws MessagingException {
        MimeMessage msg = sender.createMimeMessage();   
        MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8"); 
        message.setFrom(from);   
        message.setSubject(mail.getSubject());   
        message.setTo(mail.getTo());   
        message.setText(toHtml(mail), true); //if html true, esle false 
        
        return msg;
    }
    private String toHtml(MailInfo mail) {
        Map<String, Object> map  = new HashMap<String, Object>();
        map.put("account", (Account)mail.getData());
        map.put("site", mail.getSite());

        try {
            Template tpl =  freemarkerConfigurer.getConfiguration().getTemplate(mail.getTemplate()); 
            return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
        } catch (IOException e) {
            throw new MailException("Template \"" + mail.getTemplate() +"\" not found", e);
        } catch (TemplateException e) {
            throw new MailException(e);
        }
    }
    
    public void setFrom(String from) {
        this.from = from;
    }
    
}
